package com.example.server.service.admin.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.server.common.constant.DictConstants;
import com.example.server.common.constant.EnableConstants;
import com.example.server.common.constant.Result;
import com.example.server.entity.Dict;
import com.example.server.entity.Role;
import com.example.server.mapper.DictMapper;
import com.example.server.service.admin.DictService;
import com.example.server.vo.AddDictVO;
import com.example.server.vo.UpdateDictVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 字典(Dict)表服务实现类
 *
 * @author china.fuyao@outlook.com
 * @since 2020-03-26 11:42:31
 */
@Service("dictService")
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {
    /**
     * 新增字典
     *
     * @param addDictVO
     * @param customerId
     * @return
     */
    @Override
    @Transactional
    public Result addDict(AddDictVO addDictVO, Integer customerId) {
        Dict code = getOne(new QueryWrapper<Dict>().eq("dict_code", addDictVO.getDictCode()));
        if (null != code) {
            return Result.Error("已存在字典编码");
        }
        Dict parent = getById(addDictVO.getDictPid());
        Integer dictLevel = 1;
        String fullPath = "";
        if (null != parent) {
            if (parent.getDictLower() == DictConstants.NO_LOWER) {
                return Result.Error("不允许增加下级");
            }
            dictLevel = parent.getDictLevel() + 1;
            fullPath = parent.getDictFullPath();
        }
        Dict sd = new Dict();
        BeanUtil.copyProperties(addDictVO, sd);
        if (null == addDictVO.getDictPid()) {
            sd.setDictPid(0);
        }
        if (null == addDictVO.getDictSort()) {
            sd.setDictSort(0);
        }
        //字典等级
        sd.setDictLevel(dictLevel);
        //字典状态
        sd.setDictStatus(EnableConstants.ENABLE);
        sd.setDictLower(addDictVO.getDictLower());
        sd.setAddUid(customerId);
        sd.setUpdateUid(customerId);
        LocalDateTime date = LocalDateTime.now();
        sd.setAddTime(date);
        sd.setUpdateTime(date);
        boolean save = this.save(sd);
        if (save) {
            if (StringUtils.isNotBlank(fullPath)) {
                fullPath = fullPath + "," + sd.getDictId();
            } else {
                fullPath = "" + sd.getDictId();
            }
            boolean update = update(new UpdateWrapper<Dict>().eq("dict_id", sd.getDictId()).set("dict_full_path", fullPath));
            if (update) {
                return Result.OK("操作成功");
            }
        }
        return Result.Error("操作失败");
    }

    /**
     * 修改字典
     *
     * @param updateDictVO
     * @param customerId
     * @return
     */
    @Override
    public Result updateDict(UpdateDictVO updateDictVO, Integer customerId) {
        Dict sd = new Dict();
        BeanUtil.copyProperties(updateDictVO, sd);
        sd.setUpdateTime(LocalDateTime.now());
        sd.setUpdateUid(customerId);
        boolean update = updateById(sd);
        if (update) {
            return Result.OK("操作成功");
        }
        return Result.Error("操作失败");
    }

    /**
     * 删除字典
     *
     * @param dictId
     * @return
     */
    @Override
    public Result deleteDict(Integer dictId) {
        List<Dict> pidList = list(new QueryWrapper<Dict>().eq("dict_pid", dictId));
        if (null != pidList && pidList.size() > 0) {
            return Result.Error("存在子级,请先删除子级");
        }
        boolean remove = removeById(dictId);
        if (remove) {
            return Result.OK("操作成功");
        }
        return Result.Error("操作失败");
    }

    /**
     * 通过父级id,获取子级列表
     *
     * @param pid
     * @return
     */
    @Override
    public Result dictListByPid(Integer pid) {
        List<Dict> list = list(new QueryWrapper<Dict>().eq("dict_pid", pid).eq("dict_status", EnableConstants.ENABLE));
        Map<String, Object> map = new HashMap<>(3);
        for (Dict Dict : list) {
            map.put("tagId", Dict.getDictId());
            map.put("tagName", Dict.getDictName());
            map.put("tagCode", Dict.getDictCode());
        }
        return new Result(list);
    }

    /**
     * 通过父级key,获取子级列表
     *
     * @param pKey
     * @return
     */
    @Override
    public Result dictListByPCode(String pKey) {
        Dict Dict = getOne(new QueryWrapper<Dict>().eq("dict_code", pKey));
        return dictListByPid(Dict.getDictId());
    }

    /**
     * 启/禁用字典
     *
     * @param dictId
     * @param enable
     * @param customerId
     * @return
     */
    @Override
    public Result setEnable(Integer dictId, Integer enable, Integer customerId) {
        Dict dict = getById(dictId);
        if (null != dict) {
            dict.setDictStatus(enable);
            boolean update = updateById(dict);
            if (update) {
                return Result.OK();
            }
            return Result.Error();
        }
        return Result.Error("字典不存在");
    }
}